package com.kugou.helloworld;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import static com.kugou.test.helper.TestHelper.print;

/**
 * Created by sijiluo on 2016/6/3.
 */
public class ServiceUtil {
    private static IRemoteService miRemoteService = null;
    private static RemoteServiceConnection mConn = null;

    private static class RemoteServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            print("onServiceConnected %s", name.getPackageName());
            miRemoteService = IRemoteService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            print("onServiceDisconnected %s", name.getPackageName());
            miRemoteService = null;
        }
    }

    /**
     * 绑定服务
     *
     * @param context
     * @return
     */
    public static boolean bindToService(Context context) {
        Intent in = new Intent().setClass(context, RemoteService.class);
        print("bindService RemoteService begin");
        if (mConn == null){
            mConn = new RemoteServiceConnection();
        }
        context.getApplicationContext().bindService(in, mConn, 0);
        context.startService(new Intent(context, RemoteService.class));
        print("bindService RemoteService end");
        return true;
    }

    public static void unbindFromService(Context context){
        context.unbindService(mConn);
        mConn =  null;
        miRemoteService = null;
    }

    public static boolean isBuild(){
        return  miRemoteService!=null;
    }

    public static long getServiceRunTime(){
        long time = 0l;
        try {
            time = miRemoteService.getServiceRunTime();
        } catch (RemoteException e){
            e.printStackTrace();
        }
        return time;
    }
}
